<!-- 告警分析环形图 -->

<template>
  <div class="alarm-analysis">
    <div ref="alarmChart" class="alarm-chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'AlarmAnalysis',
  data() {
    return {
      chart: null,
      total: 0 // 预警总数
    }
  },
  props: {
    alarmData: {
      type: Object,
      default: () => null
    }
  },
  watch: {
    // 监听数据变化，更新图表
    alarmData: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initChart()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.alarmData) {
        this.initChart()
      }
      // 监听窗口大小变化，自适应调整图表
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    // 组件销毁前清理图表实例和事件监听
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    // 根据数据源生成图表数据
    generateChartData(result) {
      // 告警来源映射关系
      const sourceTypeMap = [
        {
          key: 'electric',
          name: '电气异常',
          color: '#409EFF'
        },
        {
          key: 'alarm',
          name: '运行异常',
          color: '#E6A23C'
        },
        {
          key: 'fault',
          name: '操作异常',
          color: '#F56C6C'
        },
        {
          key: 'temperature',
          name: '温度异常',
          color: '#67C23A'
        }
      ]

      // 根据数据源生成数据数组
      const chartData = sourceTypeMap.map(source => {
        const value = Number(result[source.key]) || 0
        return {
          value: value,
          name: source.name,
          itemStyle: {
            color: source.color
          }
        }
      })

      // 计算总数，用于百分比计算
      const total = chartData.reduce((sum, item) => sum + item.value, 0)

      // 为每个数据项添加百分比
      chartData.forEach(item => {
        item.percent = total > 0 ? ((item.value / total) * 100).toFixed(2) : '0.00'
      })

      return { chartData, total }
    },
    initChart() {
      // 如果没有数据，不初始化图表
      if (!this.alarmData) {
        return
      }

      // 初始化图表实例
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.alarmChart)
      }

      // 根据数据源生成图表数据
      const { chartData, total } = this.generateChartData(this.alarmData)

      // 保存总数，用于显示
      this.total = total

      // 环形图配置选项
      const option = {
        graphic: [
          {
            type: 'text',
            left: 'center',
            top: '42%',
            style: {
              text: '预警总数',
              textAlign: 'center',
              fill: '#666',
              fontSize: 14,
              fontWeight: 'normal'
            }
          },
          {
            type: 'text',
            left: 'center',
            top: '47%',
            style: {
              text: total.toString(),
              textAlign: 'center',
              fill: '#409EFF',
              fontSize: 28,
              fontWeight: 'bold'
            }
          }
        ],
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#409EFF',
          borderWidth: 1,
          padding: [10, 15],
          textStyle: {
            color: '#333',
            fontSize: 13
          },
          formatter: (params) => {
            const percent = params.data.percent || '0.00'
            return `
              <div style="font-weight: 600; color: #2d4a6b; margin-bottom: 6px;">${params.data.name}</div>
              <div style="display: flex; align-items: center;">
                <span style="display: inline-block; width: 10px; height: 10px; background-color: ${params.color}; border-radius: 50%; margin-right: 8px;"></span>
                <span style="color: #666; margin-right: 8px;">数量:</span>
                <span style="color: #333; font-weight: 600; margin-right: 12px;">${params.data.value}</span>
                <span style="color: #666;">占比:</span>
                <span style="color: #409EFF; font-weight: 600;">${percent}%</span>
              </div>
            `
          }
        },
        legend: {
          orient: 'horizontal',
          left: 'center',
          top: '8%',
          textStyle: {
            color: '#666',
            fontSize: 11
          },
          formatter: function(name) {
            return name
          }
        },
        series: [
          {
            name: '来源类型',
            type: 'pie',
            radius: ['25%', '45%'], // 内外半径，形成环形
            center: ['50%', '47%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 5,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: (params) => {
                const percent = params.data.percent || '0.00'
                return `${params.data.name}\n${params.data.value} (${percent}%)`
              },
              fontSize: 10
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: chartData
          }
        ]
      }

      // 设置配置项并渲染图表
      this.chart.setOption(option)
    },
    handleResize() {
      // 窗口大小改变时重新调整图表大小
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped>
.alarm-analysis {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.alarm-chart {
  width: 100%;
  height: 100%;
  min-height: 0;
}
</style>

